<?php
/**
 * Created by PhpStorm.
 * User: Bostin
 * Date: 2019-02-14
 * Time: 18:32
 */

namespace Bostin\Translator\Sdk;


use GuzzleHttp\Client;

/**
 * Class Baidu
 * @package Bostin\Translator\Sdk
 */
class Baidu
{
    /**
     * @var string
     */
    protected $api = 'https://fanyi-api.baidu.com/api/trans/vip/translate';

    /**
     * @var
     */
    protected $client;

    /**
     * @var string
     */
    protected $appid;

    /**
     * @var string
     */
    protected $secret;

    /**
     * @var array
     */
    protected $config;

    /**
     * Baidu constructor.
     * @param string $appid
     * @param string $secret
     * @param array $config
     */
    public function __construct(string $appid, string $secret, array $config = [])
    {
        $this->appid = $appid;
        $this->secret = $secret;
        $this->config = $config;
    }

    /**
     * @return Client
     */
    private function getClient(): Client
    {
        if (is_null($this->client)) {
            $this->client = new Client($this->config['guzzle'] ?? []);
        }
        return $this->client;
    }

    /**
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function textTranslate(string $sourceText, string $source, string $target): ?string
    {
        $result = $this->request(['q' => $sourceText, 'from' => $source, 'to' => $target]);
        return $result['trans_result'][0]['dst'];
    }

    /**
     * @param string $sourceText
     * @param int $salt
     * @return string
     */
    private function sign(string $sourceText, int $salt): string
    {
        return strtolower(md5($this->appid . $sourceText . $salt . $this->secret));
    }

    /**
     * @param array $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request(array $params): array
    {
        $salt = rand(100000, 9999999);

        $params = [
            'q' => $params['q'] ?? '',
            'from' => $params['from'] ?? 'auto',
            'to' => $params['to'] ?? 'en',
            'appid' => $this->appid,
            'salt' => $salt,
            'sign' => $this->sign($params['q'] ?? '', $salt),
        ];

        $body = (string) $this->getClient()->request('POST', $this->api, ['form_params' => $params])->getBody();
        return json_decode($body, true);
    }
}